package com.example.ycdyus.dailyfruit.utils;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AlertDialog;


import com.example.ycdyus.dailyfruit.R;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by ycdyus on 2015/10/13.
 */
public class DownApkAsync extends AsyncTask<String,Integer,File> {
    private Context context;
    //定义一个管理者
    private NotificationManager manager;
    //定义一个通知
    private NotificationCompat.Builder builders;
    private AlertDialog.Builder builder1;

    public DownApkAsync(Context context) {
        this.context = context;
        manager = (NotificationManager) context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

        builder1 = new AlertDialog.Builder(context);
        //实例化一个通知
        builders = new NotificationCompat.Builder(context);
        //设置一个图标
        builders.setSmallIcon(R.mipmap.ic_launcher);
        //设置标题的内容
        builders.setContentTitle("版本更新");
        //设置通知的内容
        builders.setContentText("正在下载");
        //加载一个进度条
        builders.setProgress(100,0, false);
        //设置滚动提示
        builders.setTicker("手游助手正在更新");
        //发起通知
        manager.notify(1,builders.build());
    }

    @Override
    protected File doInBackground(String... params) {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            try{
                int max =0;
                URL url = new URL(params[0]);
                HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                //获取到文件的大小
                max = conn.getContentLength();
                InputStream is = conn.getInputStream();
                File file = new File(Environment.getExternalStorageDirectory()+File.separator+"down");
                if(!file.exists()){
                    file.mkdirs();
                }
                file = new File(file,"update.apk");
                FileOutputStream fos = new FileOutputStream(file);
                BufferedInputStream bis = new BufferedInputStream(is);
                byte[] buffer = new byte[1024];
                int len ;
                int total=0;
                while((len =bis.read(buffer))!=-1){
                    fos.write(buffer, 0, len);
                    total+= len;
                    //获取当前下载量
                    int pro = total * 100 / max;
                    builders.setProgress(100, total * 100 / max, false);
                    if(total==max){
                        builders.setContentTitle("版本更新");
                        builders.setContentText("下载完成");
                    }
                    manager.notify(1, builders.build());
                }
                fos.close();
                bis.close();
                is.close();
                return file;
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(File s) {
        super.onPostExecute(s);
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(s), "application/vnd.android.package-archive");//编者按：此处Android应为android，否则造成安装不了
        context.startActivity(intent);
    }
}
